package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Receipt;
import com.ybkj.daijia.server.service.MemberAccountService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.ReceiptService;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "receipt")
public class ReceiptController {

    @Autowired
    private ReceiptService receiptService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private MemberAccountService memberAccountService;

    @RequestMapping(value = {"list", "/"}, method = RequestMethod.GET)
    public ModelAndView list(
        @RequestParam(required = false, value = "param") String param,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("receipt")) {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String now = formatter.format(new Date());
            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isEmpty(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                } else {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isEmpty(startTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                    cl.add(Calendar.MONTH, -1);
                    start = cl.getTime();
                } else {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }
            ModelAndView mv = new ModelAndView();
//			Page<Receipt> page = receiptService.queryAll();
            Page<Receipt> page = receiptService.findByParam(param, start, end);

            mv.addObject("param", param);
            mv.addObject("start", start);
            mv.addObject("end", end);
            mv.addObject("page", page);

            mv.setViewName("receipt/list");

            return mv;

        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "listData", method = RequestMethod.GET)
    public @ResponseBody
    Page<Receipt> listData(
        @RequestParam(required = false, value = "number") String number,
        @RequestParam(required = false, value = "phone") String phone,
        @RequestParam(required = false, value = "name") String name,
        @RequestParam(required = false, value = "startTime") String startTime,
        @RequestParam(required = false, value = "endTime") String endTime) {

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("receipt")) {
            Date start = null;
            Date end = null;
            try {
                if (StringUtils.isNotBlank(endTime)) {
                    Calendar cl = Calendar.getInstance();
                    cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                    cl.add(Calendar.HOUR_OF_DAY, 23);
                    cl.add(Calendar.MINUTE, 59);
                    cl.add(Calendar.SECOND, 59);
                    end = cl.getTime();
                }

                if (StringUtils.isNotBlank(startTime)) {
                    start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            Page<Receipt> page = receiptService.findAllByParam(name, number, phone, start, end);
            return page;

        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping(value = "toAdd", method = RequestMethod.GET)
    public ModelAndView toAdd(HttpSession session) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("receipt/add");
        return mv;
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Receipt> delete(Long id) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("receipt")) {

            Receipt receipt = receiptService.findById(id);
            Long memberId = receipt.getMemberId();
            Passenger passenger = memberService.findOnePassenger(memberId);

            Result<Receipt> result = receiptService.delete(passenger, receipt);
            return result;
        } else {
            throw new NoPermissionException();
        }
    }

    /**
     * 后台直接开票
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Receipt> create(Long passengerId, BigDecimal money,
        String memo, String billingDesc, String number) {
        Result<Receipt> result = new Result<Receipt>();
        result.setSuccess(false);

        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("receipt")) {

            Passenger passenger = memberService.findOnePassenger(passengerId);
            if (null == passenger) {
                result.setMessage("没有此客户,请重新填写!");
                return result;
            }
            //通过BigDecimal的compareTo返回的结果是int类型,-1表示小于,0是等于,1是大于.
            if (1 == BigDecimal.ZERO.compareTo(money) || 0 == BigDecimal.ZERO.compareTo(money)
                || 1 == money.compareTo(passenger.getReceiptMoney())) {
                result.setMessage("开票金额输入错误");
                return result;
            }
            Receipt receipt = new Receipt();

            receipt.setMemberId(passenger.getId());
            receipt.setMoney(money);
            receipt.setMemberName(passenger.getName());
            receipt.setMemberPhone(passenger.getPhone());
            receipt.setStatus(1);
            receipt.setBillingDate(new Date());
            receipt.setType("服务费");
            if (StringUtils.isNotBlank(memo)) {
                receipt.setMemo(memo);
            }
            if (StringUtils.isNotBlank(billingDesc)) {
                receipt.setBillingDesc(billingDesc);
            }
            if (StringUtils.isNotBlank(number)) {
                receipt.setNumber(number);
            }

            result = receiptService.createReceipt(passenger, receipt);

            return result;

        } else {
            result.setMessage("您没有该权限");
            throw new NoPermissionException();
        }
    }

    /**
     * 审核开票
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "billing", method = RequestMethod.POST)
    public String billing(@RequestParam("id") Long id, String number, String billingDesc) {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("receipt")) {
            Receipt receipt = receiptService.findById(id);
            if (receipt.getStatus() == 0) {
                receipt.setStatus(1);
                if (StringUtils.isNotBlank(number)) {
                    receipt.setNumber(number);
                }
                if (StringUtils.isNotBlank(billingDesc)) {
                    receipt.setBillingDesc(billingDesc);
                }
                receiptService.update(receipt);
            }
            return "redirect:/receipt/list";

        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping(value = {"queryReceipt"})
    public String queryNumber(String param, String startTime, String endTime, Model model) {

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String now = formatter.format(new Date());
        Date start = null;
        Date end = null;
        try {
            if (StringUtils.isEmpty(endTime)) {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                cl.add(Calendar.HOUR_OF_DAY, 23);
                cl.add(Calendar.MINUTE, 59);
                cl.add(Calendar.SECOND, 59);
                end = cl.getTime();
            } else {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(endTime, "yyyy-MM-dd"));
                cl.add(Calendar.HOUR_OF_DAY, 23);
                cl.add(Calendar.MINUTE, 59);
                cl.add(Calendar.SECOND, 59);
                end = cl.getTime();
            }

            if (StringUtils.isEmpty(startTime)) {
                Calendar cl = Calendar.getInstance();
                cl.setTime(DateUtils.parseDate(now, "yyyy-MM-dd"));
                cl.add(Calendar.MONTH, -1);
                start = cl.getTime();
            } else {
                start = DateUtils.parseDate(startTime, "yyyy-MM-dd");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }

        Page<Receipt> page = receiptService.findByParam(param, start, end);

        model.addAttribute("param", param);
        model.addAttribute("start", start);
        model.addAttribute("end", end);
        model.addAttribute("page", page);
        return "receipt/list";
    }


    @RequestMapping(value = "getMember", method = RequestMethod.GET)
    public @ResponseBody
    Map<String, Object> getMember(String phone) {
        Passenger passenger = memberService.findOnePassengerByPhone(phone);
        Map<String, Object> map = new HashMap<String, Object>();
        if (passenger != null) {
            map.put("phone", passenger.getPhone());
            map.put("name", passenger.getName());
            map.put("alreadyMoney", passenger.getReceiptMoney());
            map.put("id", passenger.getId());
        }
        return map;
    }

    @RequestMapping(value = "getMembers", method = RequestMethod.GET)
    public @ResponseBody
    List<Map<String, Object>> getMembers(String phone) {

        List<Passenger> passengers = memberService.findAllPassengersByPhone(phone);

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (Passenger passenger : passengers) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("phone", passenger.getPhone());
            map.put("id", passenger.getId());
            map.put("name", passenger.getName());
            map.put("alreadyMoney", passenger.getReceiptMoney());
            list.add(map);
        }

        return list;
    }

}
